package com.huanxing.cloud.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.common.core.constant.RocketMqConstants;
import com.huanxing.cloud.common.myabtis.tenant.HxTenantContextHolder;
import com.huanxing.cloud.order.api.entity.OrderItem;
import com.huanxing.cloud.order.api.entity.OrderRefund;
import com.huanxing.cloud.order.event.HxOrderRefundEvent;
import com.huanxing.cloud.order.service.IOrderItemService;
import com.huanxing.cloud.order.service.IOrderRefundService;
import com.huanxing.cloud.pay.api.constants.PayConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Slf4j
@RequiredArgsConstructor
@Component
@RocketMQMessageListener(topic = RocketMqConstants.PAY_REFUND_NOTIFY_TOPIC,
		consumerGroup = RocketMqConstants.PAY_REFUND_NOTIFY_TOPIC)
public class HuanxingRefundListener implements RocketMQListener<String> {

	private final IOrderRefundService orderRefundService;

	private final IOrderItemService orderItemService;

	private final ApplicationEventPublisher applicationEventPublisher;

	@Override
	public void onMessage(String message) {
		final JSONObject msg = JSONObject.parseObject(message);
		final String tenantId = msg.getString(PayConstants.TENANT_ID);
		if (!StringUtils.hasText(tenantId)) {
			log.warn("tenantId empty! ");
			return;
		}
		HxTenantContextHolder.setTenantId(tenantId);
		final String refundTradeMo = msg.getString(PayConstants.REFUND_TRADE_NO);
		if (!StringUtils.hasText(refundTradeMo)) {
			log.warn("orderNo empty! ");
			return;
		}
		OrderRefund orderRefund = orderRefundService
			.getOne(Wrappers.<OrderRefund>lambdaQuery().eq(OrderRefund::getRefundTradeNo, refundTradeMo));
		if (null == orderRefund) {
			log.warn("order not found! orderNo: " + refundTradeMo);
			return;
		}
		OrderItem orderItem = orderItemService.getById(orderRefund.getOrderItemId());
		if (null == orderItem) {
			log.warn("order item not found! orderItemId: " + orderRefund.getOrderItemId());
			return;
		}
		if (!CommonConstants.YES.equals(orderRefund.getArrivalStatus())) {
			applicationEventPublisher.publishEvent(new HxOrderRefundEvent(this, orderRefund, orderItem));
		}
	}

}
